<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
          <el-form-item label="分类名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入分类名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="显示状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择显示状态" clearable>
              <el-option v-for="dict in mall_goods_category_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['mall:goodsCategory:add']" type="primary" plain icon="Plus" @click="handleAdd()"> 新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        ref="goodsCategoryTableRef"
        v-loading="loading"
        :data="goodsCategoryList"
        row-key="id"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column label="分类名称" prop="name" />
        <el-table-column label="图片" align="center" prop="image" width="100">
          <template #default="scope">
<!-- TODO 这里一次全请求了全部图片，太影响速度了，要处理 -->
            <image-preview :src="scope.row.image[0]" :width="30" :height="30" />
          </template>
        </el-table-column>
        <el-table-column label="父分类id" align="center" prop="parentId" />
        <el-table-column label="显示状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="mall_goods_category_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sort" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['mall:goodsCategory:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button v-hasPermi="['mall:goodsCategory:add']" link type="primary" icon="Plus" @click="handleAdd(scope.row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['mall:goodsCategory:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改商品分类对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="goodsCategoryFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <image-upload v-model="form.image" />
        </el-form-item>
        <el-form-item label="父分类id" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="goodsCategoryOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            value-key="id"
            placeholder="请选择上级分类"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="显示状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in mall_goods_category_status" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }} </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GoodsCategory" lang="ts">
import { listGoodsCategory, getGoodsCategory, delGoodsCategory, addGoodsCategory, updateGoodsCategory } from '@/api/mall/goodsCategory';
import { GoodsCategoryVO, GoodsCategoryQuery, GoodsCategoryForm } from '@/api/mall/goodsCategory/types';
import useCategoryStore from "@/store/modules/category";

type GoodsCategoryOption = {
  id: number;
  name: string;
  children?: GoodsCategoryOption[];
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { mall_goods_category_status } = toRefs<any>(proxy?.useDict('mall_goods_category_status'));

const goodsCategoryList = ref<GoodsCategoryVO[]>([]);
const goodsCategoryOptions = ref<GoodsCategoryOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(false);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const goodsCategoryFormRef = ref<ElFormInstance>();
const goodsCategoryTableRef = ref<ElTableInstance>();
const categoryStore = useCategoryStore();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: GoodsCategoryForm = {
  id: undefined,
  name: undefined,
  image: undefined,
  parentId: undefined,
  status: undefined,
  sort: undefined
};

const data = reactive<PageData<GoodsCategoryForm, GoodsCategoryQuery>>({
  form: { ...initFormData },
  queryParams: {
    name: undefined,
    status: undefined,
    sort: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '分类id不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
    parentId: [{ required: true, message: '父分类id不能为空', trigger: 'blur' }],
    sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商品分类列表 */

const getList = async () => {
  loading.value = true;
  //TODO 先读取分类数据放进缓存,持久化安装不了
  // categoryStore.getCategory();
  // console.log(categoryStore.goodsCategoryList)
  //从缓存中提出数据
  // goodsCategoryList.value = categoryStore.goodsCategoryList;
  const res = await listGoodsCategory(queryParams.value);
  console.log(res)
  goodsCategoryList.value = res.data;
  loading.value = false;
};

/** 查询商品分类下拉树结构 */
const getTreeSelect = async () => {
  const res = await listGoodsCategory();
  goodsCategoryOptions.value = res.data;
};

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
};

// 表单重置
const reset = () => {
  form.value = { ...initFormData };
  goodsCategoryFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = (row?: GoodsCategoryVO) => {
  reset();
  getTreeSelect();
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = '添加商品分类';
};

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(goodsCategoryList.value, isExpandAll.value);
};

/** 展开/折叠操作 */
const toggleExpandAll = (data: GoodsCategoryVO[], status: boolean) => {
  data.forEach((item) => {
    goodsCategoryTableRef.value?.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row: GoodsCategoryVO) => {
  console.log(row);
  reset();
  await getTreeSelect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getGoodsCategory(row.id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改商品分类';
};

/** 提交按钮 */
const submitForm = () => {
  goodsCategoryFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateGoodsCategory(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addGoodsCategory(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: GoodsCategoryVO) => {
  await proxy?.$modal.confirm('是否确认删除商品分类编号为"' + row.id + '"的数据项？');
  loading.value = true;
  await delGoodsCategory(row.id).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
  getList();
});
</script>
